package com.glory.dgcpcpda.activity.mfg;

import android.os.Build;
import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.LotBatchListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.callback.CustomDialogEntityCallBack;
import com.glory.dgcpcpda.entity.AdrefListEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.LotList;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class WorkBatchEndActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvEqpWorkID)
    TextView tvEqpWorkID;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.rvLotList)
    RecyclerView rvLotList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.llEQPLayout)
    LinearLayout llEQPLayout;
    @BindView(R.id.tvCount)
    TextView tvCount;
    @BindView(R.id.etUserName)
    FreeUI_ClearEditText etUserName;
    private LotBatchListAdapter mAdapter;
    private String mEquipmentid = "";
    private int mCount = 0;
    private  List<AdrefListEntity.Adref> adreflist = new ArrayList<>() ;
    private  ArrayList<String> StepNameList = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_work_batch_begin;
    }

    @Override
    protected void initView() {
//        tvEqpWorkID.setVisibility(View.VISIBLE);
        StepNameList.clear();
        llEQPLayout.setVisibility(View.GONE);
        tvBaseSubmit.setVisibility(View.GONE);
        setMainLayout(llMain);
        tvTitle.setText("批量出站");
        tvCount.setText("计数:" + mCount);
        initRecyclerView(rvLotList,this);
        mAdapter = new LotBatchListAdapter(null, false, () -> tvCount.setText("计数:" + --mCount));
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(false);
        rvLotList.setAdapter(mAdapter);
        showCarrierLayout();

        initEdit(etLot, s -> {
            etLot.setText("");
            new Handler().postDelayed(() -> etLot.requestFocus(),500);

            if ("".equals(getText(etUserName))){
                showToast("请先输入工号",false);
                return;
            }

            if (containLot(s,mAdapter.getData())){
                showToast("当前批次已在列表中",false);
                return;
            }
            LotUtils.searchLotInfo(WorkBatchEndActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {

                    if (!response.getLOT().getSTATE().equals("正在作业")){
                        showToast("批次状态不允许",false);
                        return;
                    }
                    if(!StepNameList.contains(response.getLOT().getSTEPNAME())){
                        showToast("工序不允许", false);
                        return;
                    }
//                    //增加批量工步
//                    if (!response.getLOT().getSTEPNAME().equals("A2020")
//                            &&!response.getLOT().getSTEPNAME().equals("A2110")
//                            &&!response.getLOT().getSTEPNAME().equals("A2210")
//                            &&!response.getLOT().getSTEPNAME().equals("A4200")
//                            &&!response.getLOT().getSTEPNAME().equals("A3200")
//                            &&!response.getLOT().getSTEPNAME().equals("A9021")
//                            &&!response.getLOT().getSTEPNAME().equals("A7200")
//                            &&!response.getLOT().getSTEPNAME().equals("A9011")
//                            &&!response.getLOT().getSTEPNAME().equals("A9013")
//                            &&!response.getLOT().getSTEPNAME().equals("A9024")
//                            &&!response.getLOT().getSTEPNAME().equals("A9026")
//                            &&!response.getLOT().getSTEPNAME().equals("A1900")
//                            &&!response.getLOT().getSTEPNAME().equals("A3300")
//                            &&!response.getLOT().getSTEPNAME().equals("A6100")
//                            &&!response.getLOT().getSTEPNAME().equals("A7210")
//                            &&!response.getLOT().getSTEPNAME().equals("T1025")
////                            &&!response.getLOT().getSTEPNAME().equals("A2500")
//                            &&!response.getLOT().getSTEPNAME().equals("A5010")
//                            &&!response.getLOT().getSTEPNAME().equals("A6200")) {
//                        showToast("工序不允许",false);
//                        return;
//                    }

                    if (response.getLOT().getHOLDSTATE().equals("On")){
                        showToast("批次状态不允许",false);
                        return;
                }
                mEquipmentid = response.getLOT().getEQUIPMENTID();
                submit(s,String.valueOf(response.getLOT().getMAINQTY()));

                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t,"LOTQUERY");
                }
            });
        });
    }

    private boolean containLot(String s, List<LotInfoEntity.LotBean> data) {
        if (data.size() <= 0)
            return false;
        for (LotInfoEntity.LotBean entity : data){
            if (entity.getLOTID().equals(s))
                return true;
        }
        return false;
    }

    //获取MES动态栏位参考值
    private void showCarrierLayout() {
        FreeUI_EntityCallBack<BaseResponseBean<AdrefListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<AdrefListEntity>>
                (new TypeToken<BaseResponseBean<AdrefListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onSuccess(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    adreflist = response.body().getResponse().getBody().getADREFLIST();
                    for(int i=0;i<adreflist.size();i++)
                    {
                        StepNameList.add((adreflist.get(i).getTEXT()));
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("REFERENCETYPE","USER");
        map.addProperty("REFERENCENAME","PDA_Batch_Check_In");
        NetUtils.requestPostNet("CPC.ADREFLISTQUERY","ADREFLISTQUERY",this,map,callBack);
    }

    @Override
    protected void initData() {

    }

    @OnClick(R.id.tvBaseSubmit)
    public void onViewClicked() {
        if (mAdapter.getData().size() <= 0) {
            showToast("请先添加批次信息",false);
            return;
        }
        if (getText(etUserName).equals("")){
            showToast("请输入工号",false);
            return;
        }

        //TODO://请求接口
        showSubmitDialog(new onSubmitListener() {
            @Override
            public void setOnSubmitListener() {
                FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                        (new TypeToken<BaseResponseBean<JSONObject>>() {
                        }.getType(), getSupportFragmentManager(), WorkBatchEndActivity.this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                            showToast("出站成功",true);
                            mAdapter.getData().clear();
                            etLot.setText("");
                            mAdapter.notifyDataSetChanged();

                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<JSONObject>> response) {
                        super.onError(response);
                        loadError(response.getException(),"TRACKOUT");
                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("ACTIONTYPE","DefaultTrackOut");
                map.addProperty("EQUIPMENTID",mEquipmentid);
                map.addProperty("ISCHECKSTEPAUTHORITY",true);
//                List<LotList> lotList = new ArrayList<>();
//                for (LotInfoEntity entity : mAdapter.getData()){
//                    lotList.add(new LotList(entity.getLOT().getLOTID(),String.valueOf(entity.getLOT().getMAINQTY())));
//                }
//                map.add("LOTLIST",new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());//传批次集合
                NetUtils.mRequestPostNet("CPC.LOTTRACKOUT",getText(etUserName),"LOTTRACKOUT",WorkBatchEndActivity.this,map,callBack);
            }
        });
    }

    private void submit(String lotID,String mainQTY){
        FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), WorkBatchEndActivity.this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    showToast("出站成功",true);
                    mAdapter.addData(response.body().getResponse().getBody().getLOTLIST());
                    tvCount.setText("计数:" + mAdapter.getData().size());
                }
                etLot.setText("");
            }

            @Override
            public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"TRACKOUT");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","DefaultTrackOut");
        map.addProperty("EQUIPMENTID",mEquipmentid);
        map.addProperty("ISCHECKSTEPAUTHORITY",true);
        List<LotList> lotList = new ArrayList<>();
        lotList.add(new LotList(lotID,mainQTY));
        map.add("LOTLIST",new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());//传批次集合
        NetUtils.mRequestPostNet("CPC.LOTTRACKOUT",getText(etUserName),"LOTTRACKOUT",WorkBatchEndActivity.this,map,callBack);
//        NetUtils.requestMESPostNet("CPC.LOTTRACKOUT",WorkBatchEndActivity.this,map,callBack);
    }
}